package com.holyn.guofang.view.distinguish;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.holyn.guofang.R;
import com.holyn.guofang.model.constant.AlgorithmTypeConstant;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.BrandItemInfoWo;
import com.holyn.guofang.model.webhttp.wo.ImageWo;
import com.holyn.guofang.model.webhttp.wo.StatusWo;
import com.holyn.guofang.model.webhttp.wo.TaskIDWo;
import com.holyn.guofang.model.webhttp.wo.UserCardListWo;
import com.holyn.guofang.model.webhttp.wo.UserInfoWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.distinguish.DistinguishContract;
import com.holyn.guofang.presenter.distinguish.DistinguishPresenter;
import com.holyn.guofang.utils.FilePathUtil;
import com.holyn.guofang.utils.MD5Uitl;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.view.search.SeniorSearchActivity;
import com.holyn.guofang.viewcommon.crop.CropActivity;
import com.holyn.guofang.viewcommon.dialog.TaskPayDialog;
import com.holyn.guofang.viewcommon.dialog.ToastDialog;
import com.holyn.guofang.viewcommon.popupwindow.PopupAssistOperate;
import com.holyn.guofang.viewcommon.popupwindow.PopupSingleSelectFromBottom;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vondear.rxtools.view.dialog.RxDialogSure;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Holyn on 2017/6/13.
 */

public class SeniorDistinguishActivity extends BaseActivity implements BaseView, DistinguishContract.CommonView {
    private static final int REQUEST_ACTION_POST_TASK_ID = 0x0001;
    private static final int REQUEST_ACTION_UPLOAD_IMAGE = 0x0002;
    private static final int REQUEST_ACTION_POST_BRAND_DISTINGUISH = 0x0003;
    private static final int REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID = 0x0004;

    /**
     * 2.3.8 判断返回参数 userCard ,如果该字段 内容为空，代表卡已过期，非空则代表未过期
     */
    private static final int REQUEST_ACTION_POST_USER_INFO = 0x0005;
    /**
     * 卡已过期
     * 2.5.6 获取用户的国方卡信息,请求后只做提示
     * 1.1.1—>如果 个数 大于 0 则 ，提示  当前国方卡已过期，请前往 我的-用卡管理 激活卡。
     * 1.1.2—>如果等于0，则提示  当前国方卡已过期，请前往 我的-购国方卡 购卡。
     */
    private static final int REQUEST_ACTION_POST_USER_CARD_LIST = 0x0006;
    /**
     * 卡未过期，根据2.3.8 返回的validMethod进行判断
     * 1.1->当validMethod=0 时，弹出界面，输入的密码需要md5加密。注意这个密码是在激活卡时（我的-用卡管理），当用户选择密码验证 时，需要弹框让用户设定密码，并非登录密码。
     * 1.2->当validMethod=1 时，弹出界面，点获取验证码按钮 对应接口 2.4.17 获取任务支付验证码
     * 1.3->当validMethod=2时，空值，这个就不用弹界面了，直接调用2.4.18接口。
     */
    private static final int REQUEST_ACTION_POST_TASK_PAY_CODE = 0x0007;//2.4.17
    private static final int REQUEST_ACTION_POST_TASK_PAY = 0x0008;//2.4.18

    public static final String INTENT_KEY_IMAGE_PATH = "INTENT_IMAGE_PATH";
    public static final String INTENT_KEY_SRC_IMG_ID = "INTENT_SRC_IMG_ID";
    public static final String INTENT_KEY_MAIN_IMG_URL = "INTENT_KEY_MAIN_IMG_URL";
    public static final String INTENT_KEY_SON_IMG_URL_LIST = "INTENT_KEY_SON_IMG_URL_LIST";

    public static final int REQUEST_CODE_CROP_IMAGE = 0x0003;
    public static final int REQUEST_CODE_GET_CLASSFIY_CODE = 0x0004;
    public static final int REQUEST_CODE_IMG_PARTITION = 0x0005;//分拆组合-选择重置子图列表
    public static final int REQUEST_CODE_IMG_SIMILAR = 0x0006;//替换追加
    public static final int REQUEST_CODE_CONDITION_SELECT = 0x0007;//添加文字查询内容
    public static final int REQUEST_CODE_ALGORITHM_SELECT = 0x0008;//查询条件选择（算法、过滤状态等）

    @BindView(R.id.tv_assist_operate)
    TextView tvAssistOperate;
    @BindView(R.id.imageview)
    ImageView imageview;
    @BindView(R.id.tv_query_mode)
    TextView tvQueryMode;
    @BindView(R.id.tv_query_mode_update)
    TextView tvQueryModeUpdate;
    @BindView(R.id.tv_query_content_add)
    TextView tvQueryContentAdd;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_classfiy_select)
    TextView tvClassfiySelect;
    @BindView(R.id.tv_classfiy)
    TextView tvClassfiy;
    @BindView(R.id.tv_condition_select)
    TextView tvConditionSelect;
    @BindView(R.id.tv_condition)
    TextView tvCondition;
    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private int pageSize = 20;
    /**
     * 执行商标识别
     * @param TaskID 任务 ID，由客户端请求前产生
     * @param FrontCount 首次返回前面记录数量
     * @param QueryMode 查询方式
     * @param SrcImgID 商标源图 ID(非图片流，若该值为空或空字符串， 则需要传一个图片流)
     * @param ImgIDs 其它图文件名，可以是多个，可空，多个时用“;” 分割
     * @param CnContent 商标的中文文字
     * @param EnContent 商标的英文文字
     * @param ImageCode 商标的图形要素图形要素编码
     * @param MarkClass 类别
     * @param MarkGroup 群组
     * @param ImageQueryMode 图像识别查询算法类型
     * @param ImageAlgorithm 图像识别的查询算法
     * @param CnQueryMode 中文查询算法类型
     * @param CnAlgorithm 中文的查询算法
     * @param EnQueryMode 西文查询算法类型
     * @param EnAlgorithm 英文的查询算法
     * @param CodeQueryMode 图形要素编码查询算法类型
     * @param CodeAlgorithm 图形要素编码的查询算法
     * @param State 状态过滤（0.全部，1.有效，2.无效，3.待定）。
     * @param DateType 过滤日期（0.不过滤、1.申请日期、2.初审公告日、3.注册公告日）。
     * @param BeginDate 过滤起始日期
     * @param EndDate 过滤截止日期
     */
    Integer TaskID;
    Integer FrontCount = pageSize;
    String QueryMode = "0";
    String SrcImgID;
    String ImgIDs = "";//其它图文件名，可以是多个，可空，多个时用“;” 分割;没子图是为空
    String CnContent = "";
    String EnContent = "";
    String ImageCode = "";
    String MarkClass = "";
    String MarkGroup = "";
    String ImageQueryMode = "0";
    String ImageAlgorithm = "";
    String CnQueryMode = "";
    String CnAlgorithm = "";
    String EnQueryMode = "";
    String EnAlgorithm = "";
    String CodeQueryMode = "";
    String CodeAlgorithm = "";
    String State = "0";
    String DateType = "0";
    String BeginDate = "";
    String EndDate = "";

    private PopupAssistOperate popupAssistOperate;
    private String imagePath = "";
    private File mainImageCacheDir = FilePathUtil.getFileDir("main_image");//当替换追加主图后，主图需要下载才能进行裁剪
    private String cacheMainImageName = "main_image.jpg";
    private String cacheMainImagePath = FilePathUtil.getFileDir("main_image")+cacheMainImageName;//当替换追加主图后，主图需要下载才能进行裁剪

    private DistinguishContract.Presenter presenter;

    private List<LocalMedia> selectList = new ArrayList<>();

    private String curSelectCodeType = "";
    private String curSelectCode = "";

    private MyCountDownTimer timer;

    private PopupSingleSelectFromBottom popupSelectQueryMode;
    private List<String> queryModeList = new ArrayList<>();

    private String mainImageUrl = "";
    private ArrayList<String> sonImageUrlList = new ArrayList<>();

    private ArrayList<String> algorithmTypeCodeList = new ArrayList<>();//查询算法类别的type参数列表
    private List<List<String>> algorithmCodeListList = new ArrayList<>();

    String algorithmQueryMode = "0";//算法类型（0.相同，1.近似，2.自定义）

    private int curPopupSelectQueryModePosition = 0;

    private UserInfoWo.UserInfoBean.UserCardBean cardBean;

    private BrandItemInfoWo brandItemInfoWo;

    private TaskPayDialog passwordTaskPayDialog = null;
    private TaskPayDialog validCodeTaskPayDialog = null;

    public static void startForResult(Activity fromActivity, String imagePath, String SrcImgID, String mainImageUrl, int requestCode){
        Intent intent = new Intent(fromActivity, SeniorDistinguishActivity.class);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_IMAGE_PATH, imagePath);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID, SrcImgID);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL, mainImageUrl);
        fromActivity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_senior_distinguish;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("高级识别查询", true);
        initData();
        initView();
        initPopupAssistOperate();
        initPopupSelectQueryMode();
    }

    private void initData(){
        imagePath = getIntent().getStringExtra(INTENT_KEY_IMAGE_PATH);
        SrcImgID = getIntent().getStringExtra(INTENT_KEY_SRC_IMG_ID);
        mainImageUrl = getIntent().getStringExtra(INTENT_KEY_MAIN_IMG_URL);

        queryModeList.add("混合查询");
        queryModeList.add("图像特征");
        queryModeList.add("文字内容");

        presenter = new DistinguishPresenter(this);
        presenter.addCommonViewListener(this);

        algorithmTypeCodeList.add(AlgorithmTypeConstant.TYPE_0);
    }

    private void initView(){
        showMainImg();
    }

    private void initPopupAssistOperate() {
        popupAssistOperate = new PopupAssistOperate(SeniorDistinguishActivity.this);
        popupAssistOperate.setOnSelectListener(new PopupAssistOperate.OnSelectListener() {
            @Override
            public void onSelect(int type) {
                switch (type) {
                    case PopupAssistOperate.TYPE_ALBUM:
                        openAlbum();
                        break;
                    case PopupAssistOperate.TYPE_TAKE_PHOTO:
                        takePhoto();
                        break;
                    case PopupAssistOperate.TYPE_CROP:
                        if (TextUtils.isEmpty(imagePath)){
                            toastMsg("请先选择图片");
                        } else {
                            imageCrop();
                        }
                        break;
                    case PopupAssistOperate.TYPE_SPLIT_GROUP://分拆组合
                        ImgPartitionActivity.startForResult(SeniorDistinguishActivity.this, imagePath, SrcImgID, mainImageUrl, REQUEST_CODE_IMG_PARTITION);
                        break;
                    case PopupAssistOperate.TYPE_REPLACE_ADD://替换追加
                        ImgSimilarActivity.startForResult(SeniorDistinguishActivity.this, imagePath, SrcImgID, mainImageUrl, sonImageUrlList, REQUEST_CODE_IMG_SIMILAR);
                        break;
                    case PopupAssistOperate.TYPE_SPLIT_IMAGES://分卡图样
                        ImgAdditionalActivity.start(SeniorDistinguishActivity.this, sonImageUrlList);
                        break;

                }
            }
        });
    }

    private void initPopupSelectQueryMode(){
        popupSelectQueryMode = new PopupSingleSelectFromBottom(SeniorDistinguishActivity.this, "请选择查询方式", queryModeList);
        popupSelectQueryMode.setOnItemClickListener(new PopupSingleSelectFromBottom.OnItemClickListener() {
            @Override
            public void onItemClick(String item, int position) {
                if (! (curPopupSelectQueryModePosition == position)){
                    tvQueryMode.setText(queryModeList.get(position));
                    QueryMode = position+"";
                    /**
                     * QueryMode会决定【添加文字查询内容】与【查询条件】
                     */
                    if (position == 1){
                        tvQueryContentAdd.setTextColor(ContextCompat.getColor(SeniorDistinguishActivity.this, R.color.light_grey));
                        tvQueryContentAdd.setClickable(false);
                        tvContent.setText("温馨提示：该查询方式无法添加查询内容");
                    } else {
                        CnContent = "";
                        EnContent = "";
                        ImageCode = "";
                        tvQueryContentAdd.setTextColor(ContextCompat.getColor(SeniorDistinguishActivity.this, R.color.colorPrimary));
                        tvQueryContentAdd.setClickable(true);
                        tvContent.setText("中文：无\n英文：无\n图形要素：无");
                    }

                    algorithmTypeCodeList.clear();
                    if (position != 2){
                        algorithmTypeCodeList.add(AlgorithmTypeConstant.TYPE_0);
                    }

                    //TODO 清理相关数据
                    ImageQueryMode = "0";
                    ImageAlgorithm = "";
                    CnQueryMode = "";
                    CnAlgorithm = "";
                    EnQueryMode = "";
                    EnAlgorithm = "";
                    CodeQueryMode = "";
                    CodeAlgorithm = "";
                    State = "0";
                    DateType = "0";
                    BeginDate = "";
                    EndDate = "";

                    tvCondition.setText("算法：相同，其它：默认");
                }
                curPopupSelectQueryModePosition = position;
            }
        });
    }

    @OnClick({R.id.tv_assist_operate, R.id.tv_query_mode_update, R.id.tv_query_content_add, R.id.tv_classfiy_select, R.id.tv_condition_select, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_assist_operate:
                popupAssistOperate.showPopupWindow(tvAssistOperate);
                break;
            case R.id.tv_query_mode_update:
                popupSelectQueryMode.showPopupWindow();
                break;
            case R.id.tv_query_content_add:
                QueryContentAddActivity.startForResult(SeniorDistinguishActivity.this, REQUEST_CODE_CONDITION_SELECT);
                break;
            case R.id.tv_classfiy_select:
                ToastDialog toastDialog = new ToastDialog(SeniorDistinguishActivity.this, true, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ProductClassfiyActivity.startForResult(SeniorDistinguishActivity.this, REQUEST_CODE_GET_CLASSFIY_CODE);
                        dialog.dismiss();
                    }
                });
                toastDialog.setTvContent("商品范围数据将重置");
                toastDialog.show();
                break;
            case R.id.tv_condition_select:
                if (algorithmTypeCodeList.size() == 0){
//                    toastMsg("请先添加查询内容");
                    AlgorithmSelectActivity.startForResult(SeniorDistinguishActivity.this, false, algorithmTypeCodeList, REQUEST_CODE_ALGORITHM_SELECT,1);
                } else {
                    AlgorithmSelectActivity.startForResult(SeniorDistinguishActivity.this, false, algorithmTypeCodeList, REQUEST_CODE_ALGORITHM_SELECT);
                }
                break;
            case R.id.btn_submit:
                presenter.postUserInfo(REQUEST_ACTION_POST_USER_INFO);

//                if (TextUtils.isEmpty(SrcImgID)){
//                    presenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
//                } else {
//                    presenter.postTaskID(REQUEST_ACTION_POST_TASK_ID);
//                }
                break;
        }
    }

    private void openAlbum() {
        PictureSelector.create(SeniorDistinguishActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .isCamera(false)
                .selectionMode(PictureConfig.SINGLE)
//                .compressGrade(Luban.FIRST_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                .compress(true)// 是否压缩
//                .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
//                        .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                        .compressMaxKB(100)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
//                        .compressWH(100, 100) // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    private void takePhoto() {
        PictureSelector.create(SeniorDistinguishActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
//                .compressGrade(Luban.CUSTOM_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
//                .compressMaxKB(800)
                .compress(true)// 是否压缩
//                .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

        private void imageCrop(){
            new RxPermissions(SeniorDistinguishActivity.this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                            Uri sourceUri = Uri.fromFile(new File(imagePath));
                            startActivityForResult(CropActivity.callingIntent(SeniorDistinguishActivity.this, sourceUri), REQUEST_CODE_CROP_IMAGE);
                        }
                    });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    LogUtils.d(selectList.get(0));
                    imagePath = selectList.get(0).getCompressPath();
                    Glide.with(SeniorDistinguishActivity.this).load(imagePath).into(imageview);

                    clearDataAfterReSelectImg();
                    break;
                case REQUEST_CODE_CROP_IMAGE:
                    imagePath = data.getStringExtra(CropActivity.EXTRA_RESULT_CROP_PATH);
                    Glide.with(SeniorDistinguishActivity.this).load(imagePath)
//                            .error(R.drawable.ic_empty_image)
                            .into(imageview);

                    clearDataAfterReSelectImg();
                    break;
                case REQUEST_CODE_GET_CLASSFIY_CODE:
                    curSelectCodeType = data.getStringExtra(ProductClassfiyActivity.INTENT_KEY_SELECT_CODE_TYPE);
                    curSelectCode = data.getStringExtra(ProductClassfiyActivity.INTENT_KEY_SELECT_CODE);
                    if (curSelectCodeType.equals(ProductClassfiyActivity.TYPE_TYPE_CODE)){
                        if (curSelectCodeType.equals("全类")){
                            MarkClass = "";
                        } else {
                            MarkClass = curSelectCode;
                        }
                        MarkGroup = "";
                    } else {
                        MarkGroup = curSelectCode;
                        MarkClass = "";
                    }
                    tvClassfiy.setText("商品服务范围："+curSelectCode);
                    break;
                case REQUEST_CODE_IMG_PARTITION://分拆组合
                    SrcImgID = data.getStringExtra(INTENT_KEY_SRC_IMG_ID);
                    mainImageUrl = data.getStringExtra(INTENT_KEY_MAIN_IMG_URL);
                    sonImageUrlList.clear();
                    sonImageUrlList.addAll(data.getStringArrayListExtra(ImgPartitionPreviewActivity.INTENT_KEY_SELECT_SON_IMAGE_LIST));
                    break;
                case REQUEST_CODE_IMG_SIMILAR://替换追加
                    SrcImgID = data.getStringExtra(INTENT_KEY_SRC_IMG_ID);
                    mainImageUrl = data.getStringExtra(INTENT_KEY_MAIN_IMG_URL);

                    showLoadingDialog();
                    Observable.create(new ObservableOnSubscribe<String>() {
                        @Override
                        public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                            File file;
                            try {
                                file= Glide.with(SeniorDistinguishActivity.this).load(mainImageUrl)
                                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                        .get();
                                e.onNext(file.getPath());
                            } catch (Exception ex){
                                e.onError(ex);
                            } finally {
                                e.onComplete();
                            }

                        }
                    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                            .doOnComplete(new Action() {
                                @Override
                                public void run() throws Exception {
                                    closeLoadingDialog();
                                }
                            })
                            .subscribe(new Consumer<String>() {
                                @Override
                                public void accept(@NonNull String s) throws Exception {
                                    imagePath = s;
                                    Glide.with(SeniorDistinguishActivity.this).load(imagePath)
//                                            .error(R.drawable.ic_empty_image)
                                            .into(imageview);
                                }
                            });



                    sonImageUrlList.clear();
                    sonImageUrlList.addAll(data.getStringArrayListExtra(INTENT_KEY_SON_IMG_URL_LIST));
                    break;
                case REQUEST_CODE_CONDITION_SELECT://添加文字查询内容
                    String typeCode = data.getStringExtra(QueryContentAddActivity.INTENT_KEY_SELECT_TYPE);
                    String content = data.getStringExtra(QueryContentAddActivity.INTENT_KEY_SELECT_CONTENT);
                    if (typeCode.equals(AlgorithmTypeConstant.TYPE_ARRAY_DISTINGUISH[0])){//商标名称中文
                        if (!algorithmTypeCodeList.contains(AlgorithmTypeConstant.TYPE_1)){
                            algorithmTypeCodeList.add(AlgorithmTypeConstant.TYPE_1);
                        }
                        CnContent = content;
                    } else if (typeCode.equals(AlgorithmTypeConstant.TYPE_ARRAY_DISTINGUISH[1])){//商标名称西文
                        if (!algorithmTypeCodeList.contains(AlgorithmTypeConstant.TYPE_2)){
                            algorithmTypeCodeList.add(AlgorithmTypeConstant.TYPE_2);
                        }
                        EnContent = content;
                    } else if (typeCode.equals(AlgorithmTypeConstant.TYPE_ARRAY_DISTINGUISH[2])){//商标图形要素
                        if (!algorithmTypeCodeList.contains(AlgorithmTypeConstant.TYPE_3)){
                            algorithmTypeCodeList.add(AlgorithmTypeConstant.TYPE_3);
                        }
                        ImageCode = content;
                    }
                    tvContent.setText("中文："+ (TextUtils.isEmpty(CnContent) ? "无":CnContent)+"\n" +
                            "英文："+ (TextUtils.isEmpty(EnContent) ? "无":EnContent)+"\n" +
                            "图形要素："+ (TextUtils.isEmpty(ImageCode) ? "无":ImageCode));
                    break;
                case REQUEST_CODE_ALGORITHM_SELECT:
                    initAlgorithmSelect(data);
                    break;
            }
        }
    }

    private void initAlgorithmSelect(Intent data){
        algorithmQueryMode = data.getStringExtra(AlgorithmSelectActivity.INTENT_KEY_ALGORITHM_MODE);
        algorithmCodeListList = (List<List<String>>) data.getSerializableExtra(AlgorithmSelectActivity.INTENT_KEY_ALGORITHM_TYPE_LIST);
        for (int i = 0; i<algorithmTypeCodeList.size(); i++){
            String algorithmTypeCode = algorithmTypeCodeList.get(i);
            if (algorithmTypeCode.equals(AlgorithmTypeConstant.TYPE_0)){//图像图形
                ImageQueryMode = algorithmQueryMode;
                if (algorithmQueryMode.equals("2")){//自定义
                    ImageAlgorithm = getAlgorithmCodeStrFromList(algorithmCodeListList.get(i));
                } else {//相同或者近似
                    ImageAlgorithm = "";
                }
            } else if(algorithmTypeCode.equals(AlgorithmTypeConstant.TYPE_1)){//商标名称中文
                CnQueryMode = algorithmQueryMode;
                if (algorithmQueryMode.equals("2")){//自定义
                    CnAlgorithm = getAlgorithmCodeStrFromList(algorithmCodeListList.get(i));
                } else {//相同或者近似
                    CnAlgorithm = "";
                }
            } else if(algorithmTypeCode.equals(AlgorithmTypeConstant.TYPE_2)){//商标名称西文
                EnQueryMode = algorithmQueryMode;
                if (algorithmQueryMode.equals("2")){//自定义
                    EnAlgorithm = getAlgorithmCodeStrFromList(algorithmCodeListList.get(i));
                } else {//相同或者近似
                    EnAlgorithm = "";
                }
            } else if(algorithmTypeCode.equals(AlgorithmTypeConstant.TYPE_3)){//商标图形要素
                CodeQueryMode = algorithmQueryMode;
                if (algorithmQueryMode.equals("2")){//自定义
                    CodeAlgorithm = getAlgorithmCodeStrFromList(algorithmCodeListList.get(i));
                } else {//相同或者近似
                    CodeAlgorithm = "";
                }
            }
        }

        State = data.getStringExtra(AlgorithmSelectActivity.INTENT_KEY_FILTER_STATE);
        DateType = data.getStringExtra(AlgorithmSelectActivity.INTENT_KEY_DATA_TYPE);
        BeginDate = data.getStringExtra(AlgorithmSelectActivity.INTENT_KEY_BEGIN_DATA);
        EndDate = data.getStringExtra(AlgorithmSelectActivity.INTENT_KEY_END_DATA);

        String algorithmQueryModeName = "相同";
        String otherName = "默认";
        if (algorithmQueryMode.equals("2")){//自定义
            algorithmQueryModeName = "自定义";
        } else if (algorithmQueryMode.equals("1")){//近似
            algorithmQueryModeName = "近似";
        } else if (algorithmQueryMode.equals("0")){//相同
            algorithmQueryModeName = "相同";
        }
        if (State.equals("0") && DateType.equals("0")){
            otherName = "默认";
        } else {
            otherName = "自定义";
        }
        tvCondition.setText("算法："+algorithmQueryModeName+"，其它："+otherName);

    }

    private String getAlgorithmCodeStrFromList(List<String> algorithmCodeList){
        String result = "";
        for (String algorithmCode: algorithmCodeList){
            if (TextUtils.isEmpty(result)){
                result = result + algorithmCode;
            } else {
                result = result + ";" + algorithmCode;
            }
        }
        return result;
    }

    @Override
    public void requestStart(Integer requestAction) {
        switch (requestAction){
            case REQUEST_ACTION_POST_USER_INFO:
            case REQUEST_ACTION_POST_TASK_PAY:
            case REQUEST_ACTION_POST_TASK_PAY_CODE:
                showLoadingDialog();
                break;
        }
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        closeLoadingDialog();
    }

    @Override
    public void requestComplete(Integer requestAction) {

    }

    @Override
    public void responseSuccess(int requestAction, UserInfoWo userInfoWo) {
        if (userInfoWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            cardBean = userInfoWo.getUserInfo().getUserCard();
            if (cardBean == null){//代表卡已过期
                presenter.postUserCardList(REQUEST_ACTION_POST_USER_CARD_LIST, 2, -1, -1);//请求后只做提示
            } else {//未过期
                if (TextUtils.isEmpty(SrcImgID)){
                    presenter.uploadImage(REQUEST_ACTION_UPLOAD_IMAGE, imagePath);
                } else {
                    presenter.postTaskID(REQUEST_ACTION_POST_TASK_ID);
                }
            }
        } else {
            closeLoadingDialog();
            toastMsg("获取用户详情失败");
        }

    }

    @Override
    public void responseSuccess(int requestAction, UserCardListWo userCardListWo) {
        if (userCardListWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            List<UserCardListWo.DataBean> dataBeanList = userCardListWo.getData();
            if (dataBeanList == null){
                toastMsg("当前国方卡已过期，请前往 我的-购国方卡 购卡");
            } else {
                if (dataBeanList.size() == 0){
                    toastMsg("当前国方卡已过期，请前往 我的-购国方卡 购卡");
                } else {
                    toastMsg("当前国方卡已过期，请前往 我的-用卡管理 激活卡");
                }
            }
        } else {
            toastMsg("获取获取用户的国方卡信息失败");
        }
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(Integer requestAction, TaskIDWo taskIDWo) {
        if (taskIDWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            TaskID = taskIDWo.getTaskID();

            ImgIDs = mainImageUrl.substring(mainImageUrl.lastIndexOf("/")+1);
            for (String url: sonImageUrlList){
                ImgIDs = ImgIDs + ";" +url.substring(url.lastIndexOf("/")+1);
            }

            presenter.postBrandDistingush(REQUEST_ACTION_POST_BRAND_DISTINGUISH,
                    TaskID,
                    FrontCount,
                    QueryMode,
                    SrcImgID,
                    ImgIDs,
                    CnContent,
                    EnContent,
                    ImageCode,
                    MarkClass,
                    MarkGroup,
                    ImageQueryMode,
                    ImageAlgorithm,
                    CnQueryMode,
                    CnAlgorithm,
                    EnQueryMode,
                    EnAlgorithm,
                    CodeQueryMode,
                    CodeAlgorithm,
                    State,
                    DateType,
                    BeginDate,
                    EndDate);

            timer = new MyCountDownTimer();
//            timer.start();
        } else {
            closeLoadingDialog();
            toastMsg("获取任务ID失败");
        }
    }

    @Override
    public void responseSuccess(Integer requestAction, ImageWo imageWo) {
        if (imageWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            SrcImgID = imageWo.getSrcImgID();
            mainImageUrl = imageWo.getUrl();
            presenter.postTaskID(REQUEST_ACTION_POST_TASK_ID);
        } else {
            closeLoadingDialog();
            toastMsg("上传图片失败");
        }
    }

    @Override
    public void responseSuccess(Integer requestAction, BrandItemInfoWo brandItemInfoWo) {
        if (requestAction == REQUEST_ACTION_POST_BRAND_DISTINGUISH){
//            timer.cancel();
        }

        if (brandItemInfoWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            this.brandItemInfoWo = brandItemInfoWo;
            int validMethod = cardBean.getValidMethod();
            if (validMethod == 0){//弹出dialog，输入支付密码，再支付
                closeLoadingDialog();
                showPasswordTaskPayDialog();
            } else if (validMethod == 1){//弹出dialog，输入验证码，再支付
                closeLoadingDialog();
                showValidCodeTaskPayDialog();
            } else if (validMethod == 2){//直接支付
                presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, TaskID, "");
            }

        } else {
/******************************注释学习错误❌弹窗信息！**********************************************/
            //      RxDialogSure rxDialogSure = new RxDialogSure(this);
            //      rxDialogSure.setContent("wangning!!!");
            //提示弹窗
            final RxDialogSure rxDialogSure = new RxDialogSure(this);
            rxDialogSure.getIvLogo().setImageResource(R.drawable.logo);
            rxDialogSure.setTitle("❌错误❌");
//            rxDialogSure.setContent("json\n"+brandItemInfoWo);
            rxDialogSure.setContent("status："+brandItemInfoWo.getStatus()+"\n"+"error：\n"+brandItemInfoWo.getErr()+"\n\n'brandItemInfoWo'："+brandItemInfoWo);
            rxDialogSure.getTvSure().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    rxDialogSure.cancel();
                }
            });
            rxDialogSure.show();
/******************************注释学习错误❌弹窗信息！**********************************************/
            //toastMsg("商标识别查询失败");
            closeLoadingDialog();
        }
    }

    @Override
    public void responseSuccess(int requestAction, StatusWo statusWo) {
        closeLoadingDialog();
        if (requestAction == REQUEST_ACTION_POST_TASK_PAY_CODE){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                toastMsg("成功发送支付验证码");
            } else {
                toastMsg("发送支付验证码失败");
            }
        } else if (requestAction == REQUEST_ACTION_POST_TASK_PAY){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                SearchResultListActivity.start(SeniorDistinguishActivity.this, brandItemInfoWo, TaskID);
            } else {
                toastMsg("支付失败");
            }
        }

    }

    //TODO: 重新选择图片或者图片剪切后，刷新数据
    private void clearDataAfterReSelectImg(){
        SrcImgID = "";
        mainImageUrl = "";
        sonImageUrlList.clear();
    }

    private void showMainImg(){
        if (TextUtils.isEmpty(mainImageUrl)){
            Glide.with(SeniorDistinguishActivity.this).load(imagePath)
//                    .error(R.drawable.ic_empty_image)
                    .into(imageview);
        } else {
            Glide.with(SeniorDistinguishActivity.this).load(mainImageUrl)
//                    .error(R.drawable.ic_empty_image)
                    .into(imageview);
        }
    }

    private void showPasswordTaskPayDialog(){
        if (passwordTaskPayDialog == null){
            passwordTaskPayDialog = new TaskPayDialog(SeniorDistinguishActivity.this, TaskPayDialog.STATUS_PASSWORD,
                    new TaskPayDialog.OnSureClickListener(){

                        @Override
                        public void onSureClick(String value) {
                            presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, TaskID, MD5Uitl.getMd5Value(value));
                            passwordTaskPayDialog.dismiss();
                        }
                    });
        }
        passwordTaskPayDialog.show();
    }

    private void showValidCodeTaskPayDialog(){
        if (validCodeTaskPayDialog == null){
            validCodeTaskPayDialog = new TaskPayDialog(SeniorDistinguishActivity.this, TaskPayDialog.STATUS_VALID_CODE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            presenter.postTaskPayCode(REQUEST_ACTION_POST_TASK_PAY_CODE);
                        }
                    },
                    new TaskPayDialog.OnSureClickListener() {
                        @Override
                        public void onSureClick(String value) {
                            presenter.postTaskPay(REQUEST_ACTION_POST_TASK_PAY, TaskID, value);
                            validCodeTaskPayDialog.dismiss();
                        }
                    });
        }
    }

    private class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer() {
            this(30000, 1000);
        }

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            /**
             * 如果30秒无数据返回，则中断改请求，执行2.4.13（请求获取商标查询结果）
             */
            presenter.dispose(REQUEST_ACTION_POST_BRAND_DISTINGUISH);
            toastMsg("后台响应时间过长，查询时间已超过30秒，无数据返回，请用户稍后通过【我的->处理进程】中对照您的查询时间进行查看后台处理结果！谢谢合作！",1);
            presenter.postSearchResultByTaskID(REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID, TaskID, "", 1, pageSize);

        }
    }
}
